<template>
  <div v-loading="loading">
    <div class="receipt-order-edit-wrapper app-container" style="margin-bottom: 60px">
      <el-card header="产品基本信息">
        <el-form label-width="108px" :model="form" ref="checkForm" :rules="rules">
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="产品ID" prop="product_id">
                <el-input class="w200" v-model="form.product_id" placeholder="产品ID"
                          :disabled="!isNew"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="产品名称" prop="product_name">
                <el-input class="w200" v-model="form.product_name" placeholder="产品名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="产品状态" prop="status">
                <el-select v-model="form.status" placeholder="请选择状态"
                           filterable>
                  <el-option v-for="item in statusDict" :key="Number(item.value)" :label="item.label"
                             :value="Number(item.value)"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="!isNew">
              <el-form-item label="创建时间" prop="creation_date">
                <el-input class="w200" v-model="form.creation_date" placeholder="创建时间"
                          :disabled="!isNew"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="产品描述" prop="description">
                <el-input
                  v-model="form.description"
                  placeholder="备注...100个字符以内"
                  rows="4"
                  maxlength="100"
                  type="textarea"
                  show-word-limit="show-word-limit"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="版本号" prop="version">
                <el-input v-model="form.version" :controls="false" :precision="0"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <el-card header="配方明细" class="mt10">
        <div class="receipt-order-content">
          <div class="flex-space-between mb8">
            <el-button type="primary" plain="plain" size="default" @click="handleAdd" icon="Plus">
              新增原料
            </el-button>
          </div>
          <el-table :data="form.formula" border empty-text="暂无配方明细" @row-click="handleRowClick">
            <el-table-column label="原料ID" prop="material_id">
              <template #default="scope">
                <el-input
                  v-model="scope.row.material_id"
                  placeholder="请输入原料ID"
                  v-if="isEditRow === scope.$index"
                ></el-input>
                <div v-else>{{ scope.row.material_id }}</div>
              </template>
            </el-table-column>
            <el-table-column label="原料名称" prop="material_name">
              <template #default="scope">
                <el-input
                  v-model="scope.row.material_name"
                  placeholder="请输入原料名称"
                  v-if="isEditRow === scope.$index"
                ></el-input>
                <div v-else>{{ scope.row.material_name }}</div>
              </template>
            </el-table-column>
            <el-table-column label="所需数量" prop="quantity_required">
              <template #default="scope">
                <el-input
                  v-model="scope.row.quantity_required"
                  placeholder="请输入原料名称"
                  v-if="isEditRow === scope.$index"
                ></el-input>
                <div v-else>{{ scope.row.quantity_required }}</div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template #default="scope">
                <el-button icon="Delete" type="danger" plain size="small"
                           @click="handleDeleteDetail(scope.$index)" link>删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>
    <div class="footer-global">
      <div class="btn-box">
        <div align="right">
          <el-button @click="save" type="primary">
            <div v-if="!isNew">更新</div>
            <div v-else>创建</div>
          </el-button>
          <el-button @click="cancel" class="mr10" align="right">取消</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="ProductDetail">
import {getCurrentInstance, onMounted, reactive, ref, toRefs} from "vue";
import {GetProductDetail, UpdateProduct, CreateProduct, ProductList} from "@/api/wms-django/product/product"
import {ElMessage} from "element-plus";
import {useRoute} from "vue-router";

const {proxy} = getCurrentInstance();
const loading = ref(false)
const isNew = ref(null)
const checkForm = ref()
const initFormData = {
  product_id: undefined,
  product_name: undefined,
  version: undefined,
  description: undefined,
  creation_date: undefined,
  status: undefined,
  formula: [],
}

const templateRow = {
  id: undefined,
  material_id: undefined,
  material_name: undefined,
  quantity_required: undefined,
  product: ''
}

const statusDict = ref([
  {
    label: '设计阶段',
    value: '1'
  },
  {
    label: '测试阶段',
    value: '2'
  },
  {
    label: '生产阶段',
    value: '3'
  },
  {
    label: '上市阶段',
    value: '4'
  }
])
const isEditRow = ref(false)
const isEditColumn = ref(false)

const validateProductID = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入产品ID'))
  } else {
    ProductList({'product_id': value}).then((res) => {
      if (res.data.length != 0 && isNew.value){
        callback(new Error('该产品ID已存在'))
      } else {
        callback()
      }
    })
  }
};

const data = reactive({
  form: {...initFormData},
  rules: {
    product_id: [
      { validator: validateProductID, trigger: 'blur' }
    ],
    product_name: [
      {required: true, message: "产品名称不能为空", trigger: "blur"}
    ],
    version: [
      {required: true, message: "请填写当前版本号", trigger: ['blur', 'change']}
    ],
    status: [
      {required: true, message: "请选择当前产品状态", trigger: ['blur', 'change']}
    ],
  }
});
const {form, rules} = toRefs(data);

const cancel = async () => {
  await proxy?.$modal.confirm('确认取消吗？');
  close()
}
const close = () => {
  const obj = {path: "/Product"};
  proxy?.$tab.closeOpenPage(obj);
}

const save = async () => {
  let msg = isNew.value ? '新建产品':'修改产品'
  await proxy?.$modal.confirm('确认'+ msg + '？');
  doSave()
}

const getParams = () => {
  let formula = []
  if (form.value.formula?.length) {
    // 构建参数
    formula = form.value.formula.map(it => {
      const base = {
        material_id: it.material_id,
        material_name: it.material_name,
        quantity_required: it.quantity_required,
      }
      // 只有当 it.id 存在时才添加 id 字段
      return it.id ? { ...base, id: it.id } : base
    })
  }
  return  {
    product_id: form.value.product_id,
    product_name: form.value.product_name,
    status: form.value.status,
    description: form.value.description,
    creation_date: form.value.creation_date? form.value.creation_date:new Date().toISOString().split('T')[0],
    version: form.value.version,
    formula: formula
  }
}

const doSave = () => {
  //验证shipmentForm表单
  checkForm.value?.validate((valid) => {
    // 校验
    if (!valid) {
      return ElMessage.error('请填写必填项')
    }
    const params = getParams();
    loading.value = true
    if (isNew.value) {
      CreateProduct(params).then((res) => {
        if (res.status === 201) {
          ElMessage.success(res.statusText)
          close()
        } else {
          ElMessage.error(res.statusText)
        }
      }).finally(() => {
        loading.value = false
      })
    } else {
      UpdateProduct(params.product_id, params).then((res) => {
        if (res.status === 200) {
          ElMessage.success(res.statusText)
          close()
        } else {
          ElMessage.error(res.statusText)
        }
      }).finally(() => {
        loading.value = false
      })
    }
  })
}

const route = useRoute();
onMounted(() => {
  const id = route.query && route.query.id;
  if (id) {
    loadDetail(id)
  } else {
    isNew.value = true
  }
  document.addEventListener('click', handleClickOutside);
})


// 获取入库单详情
const loadDetail = (id) => {
  loading.value = true
  GetProductDetail(id).then((response) => {
    form.value = {...response.data}
    Promise.resolve();
  }).then(() => {
  }).finally(() => {
    loading.value = false
  })
}

const handleDeleteDetail = (index) => {
  proxy.$modal.confirm('确认删除该配方吗？').then(function () {
    form.value.formula.splice(index, 1)
  })
}

const handleAdd = () => {
  form.value.formula.push({...templateRow});
}

const handleRowClick = (row, column, event) => {
  event.stopPropagation();
  isEditRow.value = form.value.formula.indexOf(row)
};


const handleClickOutside = (event) => {
  const tableEl = document.querySelector('.el-table'); // 获取表格元素，根据你的实际类名调整
  const clickedInsideTable = tableEl && tableEl.contains(event.target);

  if (!clickedInsideTable) {
    isEditRow.value = -1;
  }
};

</script>

<style lang="scss" scoped>
@import "@/assets/styles/variables.module";

.btn-box {
  width: calc(100% - #{$base-sidebar-width});
  display: flex;
  align-items: center;
  justify-content: flex-end;
  float: right;
}

.el-statistic__content {
  font-size: 14px;
}
.hover-text {
  color: black; /* 初始文字颜色 */
  text-decoration: none; /* 初始没有下划线 */
  transition: color 0.3s, text-decoration 0.3s; /* 平滑过渡效果 */
}

.hover-text:hover {
  color: #409EFF; /* 鼠标移上去时文字颜色变为蓝色 */
  text-decoration: underline; /* 鼠标移上去时带有下划线 */
}
</style>
